package org.fujene.structure;

import java.util.ArrayList;

public class ContentInfo {
	private String[] contentNames;
	private String[] supplementNames;
	private int[][] graph;

	public ContentInfo(String[] contentName, String[] supplementName) {
		this.contentNames = contentName;
		this.supplementNames = supplementName;
		graph = new int[contentName.length][];
	}

	// 紐付けを接続
	public void connectGraph(int contentIndex, int[] supplementVector) {
		if (contentIndex < contentNames.length) {
			graph[contentIndex] = supplementVector;
		}
	}

	public String getContentName(int index) {
		if (index < contentNames.length)
			return contentNames[index];
		else
			return null;
	}

	public int getContentIndex(String str) {
		for (int i = 0; i < contentNames.length; i++) {
			if (contentNames[i].equals(str)) {
				return i;
			}
		}

		return -1;
	}

	public String getSupplementName(int index) {
		if (index < supplementNames.length)
			return contentNames[index];
		else
			return null;
	}

	public int getSupplementIndex(String str) {
		for (int i = 0; i < supplementNames.length; i++) {
			if (supplementNames.equals(str)) {
				return i;
			}
		}

		return -1;
	}

	public int getConnectionNum(int index) {
		if (graph == null || graph.length >= index)
			return 0;
		else if (graph.length != 0)
			return graph[index].length;
		else
			return 0;
	}

	// 最適化
	public void optimize() {
		if (graph == null)
			return;

		int[] filled = new int[contentNames.length];

		for (int i = 0; i < graph.length; i++) {
			if(graph[i] != null){
				for (int j = 0; j < graph[i].length; j++) {
					filled[graph[i][j]] = 1;
				}
			}
		}

		ArrayList<String> newSupp = new ArrayList<String>();
		ArrayList<Integer> renumber = new ArrayList<Integer>();
		for (int i = 0; i < filled.length; i++) {
			if (filled[i] == 1) {
				// つながってる！
				newSupp.add(supplementNames[i]);
				renumber.add(Integer.valueOf(i));
			}
		}

		// いらない追加情報は消す
		supplementNames = newSupp.toArray(new String[newSupp.size()]);

		// リナンバリング
		for (int i = 0; i < graph.length; i++) {
			if(graph[i] != null){
				for (int j = 0; j < graph[i].length; j++) {
					graph[i][j] = renumber.indexOf(Integer.valueOf(graph[i][j]));
				}
			}
		}
	}

	public int getContentNum() {
		return contentNames.length;
	}

	public int getSupplementNum() {
		return supplementNames.length;
	}

	public LookupPointer[] constructIndex(LookupPointer[] suppPtrs,
			int contentIndex) {
		if (suppPtrs.length > 0) {
			LookupPointer[] retPtrs = new LookupPointer[graph[contentIndex].length];

			for (int i = 0; i < retPtrs.length; i++) {
				retPtrs[i] = suppPtrs[graph[contentIndex][i]];
			}

			return retPtrs;
		} else
			return null;
	}
}
